package com.will.yuaiagent.app;

import com.will.yuaiagent.advisor.MyLoggerAdvisor;
import com.will.yuaiagent.rag.LoveAppRagCustomAdvisorFactory;
import com.will.yuaiagent.rag.QueryRewriter;
import com.will.yuaiagent.rag.QueryTranslationRewriter;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.ChatMemoryRepository;
import org.springframework.ai.chat.memory.InMemoryChatMemoryRepository;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author will
 * @since 2025/6/27 12:00
 */
@Component
@Slf4j
public class LoveApp {

    private final ChatClient chatClient;

    private static final String SYSTEM_PROMPT = "扮演深耕恋爱心理领域的专家。开场向用户表明身份，告知用户可倾诉恋爱难题。" +
            "围绕单身、恋爱、已婚三种状态提问：单身状态询问社交圈拓展及追求心仪对象的困扰；" +
            "恋爱状态询问沟通、习惯差异引发的矛盾；已婚状态询问家庭责任与亲属关系处理的问题。" +
            "引导用户详述事情经过、对方反应及自身想法，以便给出专属解决方案。";

    /**
     * 构造函数，初始化ChatClient
     * @param dashscopeChatModel 自动注入的aiChat模型
     */
    public LoveApp(ChatModel dashscopeChatModel) {
        //初始化基于文件的对话记忆
//        String fileDir = System.getProperty("user.dir") + "/tem/chat-memory";
//        ChatMemory fileChatMemory = new FileBasedChatMemory(fileDir);
        // 初始化基于内存的对话记忆
        ChatMemoryRepository chatMemoryRepository = new InMemoryChatMemoryRepository();
        //ChatMemory目前有一个内置实现：MessageWindowChatMemory,MessageWindowChatMemory基于一个消息窗口，该窗口大小为20，即最多存储20条消息。
        //MessageWindowChatMemory由ChatMemoryRepository提供聊天对话内存存储实现的抽象支持。
        //目前有多种实现可用，包括InMemoryChatMemoryRepository和JdbcChatMemoryRepository,CassandraChatMemoryRepository,Neo4jChatMemoryRepository
        ChatMemory chatMemory = MessageWindowChatMemory.builder()
                .chatMemoryRepository(chatMemoryRepository)
                .maxMessages(10)
                .build();
        chatClient = ChatClient.builder(dashscopeChatModel)
                .defaultSystem(SYSTEM_PROMPT)
                .defaultAdvisors(
                        new SimpleLoggerAdvisor()
                        //new MyLoggerAdvisor()
                )
                .defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build())
                .build();
    }

    /**
     * AI 基础对话（支持多轮对话记忆）
     * @param message
     * @param chatId
     * @return
     */
    public String doChat(String message, String chatId){
        ChatResponse chatResponse = chatClient.prompt()
                .user(message)
                .advisors(advisorSpec -> advisorSpec.param(ChatMemory.CONVERSATION_ID, chatId))
                .call()
                .chatResponse();

        String content = chatResponse != null ? chatResponse.getResult().getOutput().getText() : null;
        log.info("content: {}", content);
        return content;
    }

    /**
     * AI 基础对话（支持多轮对话记忆, SSE流式传输）
     * @param message
     * @param chatId
     * @return
     */
    public Flux<String> doChatByStream(String message, String chatId){
        return chatClient.prompt()
                .user(message)
                .advisors(advisorSpec -> advisorSpec.param(ChatMemory.CONVERSATION_ID, chatId))
                .stream()
                .content();
    }

    record LoveReport(String title, List<String> content) {// 定义一个LoveReport类(java21新特性)
    }

    public LoveReport doChatWithReport(String message, String chatId) {
        LoveReport loveReport = chatClient
                .prompt()
                .system(SYSTEM_PROMPT + "每次对话后都要生成恋爱结果，标题为{用户名}的恋爱报告，内容为建议列表")
                .user(message)
                .advisors(spec -> spec.param(ChatMemory.CONVERSATION_ID, chatId))
                .call()
                .entity(LoveReport.class);
        log.info("loveReport: {}", loveReport);
        return loveReport;
    }


    @Resource
    private VectorStore loveAppVectorStore;

    @Resource
    private Advisor loveAppRagCloudAdvisor;

    @Resource
    private VectorStore pgVectorVectorStore;

    @Resource
    private QueryRewriter queryRewriter;

    @Resource
    private QueryTranslationRewriter queryTranslationRewriter;

    /**
     * 和Rag 知识库进行对话
     * @param message
     * @param chatId
     * @return
     */
    public String doChatWithRag(String message, String chatId){
        // 查询重写
        //message = queryRewriter.doQueryRewrite(message);
        //查询翻译
        //message = queryTranslationRewriter.doQueryTranslation(message);

        ChatResponse chatResponse = chatClient.prompt()
                .user(message)
                .advisors(advisorSpec -> advisorSpec.param(ChatMemory.CONVERSATION_ID, chatId))
                //添加日志
                .advisors(new MyLoggerAdvisor())
                //应用RAG知识库问答
                .advisors(new QuestionAnswerAdvisor(loveAppVectorStore))
                //应用RAG检索增强顾问（基于云知识库）
                //.advisors(loveAppRagCloudAdvisor)
                //应用RAG检索增强顾问（基于PgVector向量存储）
                //.advisors(new QuestionAnswerAdvisor(pgVectorVectorStore))

                //应用RAG检索增强顾问（自定义文档查询器+上下文增强）
//                .advisors(
//                        LoveAppRagCustomAdvisorFactory.createLoveAppRagCustomAdvisor(
//                                loveAppVectorStore,"已婚"
//                        )
//                )
                .call()
                .chatResponse();

        String content = chatResponse != null ? chatResponse.getResult().getOutput().getText() : null;
        log.info("content: {}", content);
        return content;
    }

    //Ai function call
    @Resource
    private ToolCallback[] allTools;

    public String doChatWithTools(String message, String chatId) {
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(ChatMemory.CONVERSATION_ID, chatId))
                .advisors(new MyLoggerAdvisor())
                .toolCallbacks(allTools)
                .call()
                .chatResponse();
        String text = chatResponse.getResult().getOutput().getText();
        log.info("content:{}", text);
        return text;
    }

    //ai 调用MCP服务
    @Resource
    private ToolCallbackProvider asyncToolCallbacks;

    public String doChatWithMCP(String message, String chatId) {
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(ChatMemory.CONVERSATION_ID, chatId))
                .advisors(new MyLoggerAdvisor())
                .toolCallbacks(asyncToolCallbacks)
                .call()
                .chatResponse();
        String text = chatResponse.getResult().getOutput().getText();
        log.info("content:{}", text);
        return text;
    }
}
